package com.lbd99.data.utils;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.document.AbstractExcelView;

/**
 * 前台导出数据到Excel的工具类
 */
public class ViewExcel extends AbstractExcelView {
    /**
     * 整形数据样式
     */
    private static HSSFCellStyle integerStyle = null;
    /**
     * 双精度数据样式
     */
    private static HSSFCellStyle doubleStyle = null;
    /**
     * 百分比形式的数据样式
     */
    private static HSSFCellStyle bigdecimalStyle = null;
    /**
     * 长整形数据样式
     */
    private static HSSFCellStyle longStyle = null;
    /**
     * 浮点数据样式
     */
    private static HSSFCellStyle floatStyle = null;

    @Override
    protected void buildExcelDocument(Map<String, Object> model,
                                      HSSFWorkbook workbook, HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
        String fileName = (String) model.get("fileName");//文件名
        Object[][] objs = (Object[][]) model.get("objs");//表格内容
        HSSFSheet sheet = workbook.createSheet(fileName);
        String headString = (String) model.get("tableHead");//表头
        String[] headArray = headString.split(",");
        // 新建表头row
        HSSFRow row = createRow(sheet, 0, 24);
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 表头设置居中
        style.setAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//
        // 设置前景色
        style.setFillForegroundColor(HSSFColor.YELLOW.index);
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//
        style.setFont(font);
        // 新建表头列
        for (int i = 0; i < headArray.length; i++) {
            HSSFCell cell = createCell(row, i);
            if (headArray[i] != null) {
                cell.setCellValue(headArray[i].toString());
                cell.setCellStyle(style);
            }
        }
        // 新建表内容行
        for (int i = 0; i < objs.length; i++) {
            HSSFRow dataRow = null;
            dataRow = createRow(sheet, i + 1, 24);
            for (int j = 0; j < objs[i].length; j++) {
                HSSFCell dataCell = createCell(dataRow, j);
                setCellVal(dataCell, objs[i][j], workbook);
            }
        }

        String filename = fileName + ".xls";//设置下载时客户端Excel的名称
        filename = encodeFilename(filename, request);//处理中文文件名
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        OutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

    /**
     * 设置下载文件中文件的名称
     *
     * @param filename
     * @param request
     * @return
     */
    public static String encodeFilename(String filename, HttpServletRequest request) {
        /**
         * 获取客户端浏览器和操作系统信息
         * 在IE浏览器中得到的是：User-Agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; Alexa Toolbar)
         * 在Firefox中得到的是：User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.7.10) Gecko/20050717 Firefox/1.0.6
         */
        String agent = request.getHeader("USER-AGENT");
        try {
            if ((agent != null) && (-1 != agent.indexOf("MSIE"))) {
                String newFileName = URLEncoder.encode(filename, "UTF-8");
                newFileName = StringUtils.replace(newFileName, "+", "%20");
                if (newFileName.length() > 150) {
                    newFileName = new String(filename.getBytes("GB2312"), "ISO8859-1");
                    newFileName = StringUtils.replace(newFileName, " ", "%20");
                }
                return newFileName;
            }
            if ((agent != null) && (-1 != agent.indexOf("Mozilla")))
                return MimeUtility.encodeText(filename, "UTF-8", "B");

            return filename;
        } catch (Exception ex) {
            return filename;
        }
    }

    private static HSSFSheet createSheet(HSSFWorkbook wb, String sheetName) {
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(12);
        sheet.setGridsPrinted(true);
        sheet.setDisplayGridlines(true);
        return sheet;
    }

    /**
     * 创建HSSFRow
     *
     * @param sheet
     * @param rownum
     * @param height
     * @return
     */
    private static HSSFRow createRow(HSSFSheet sheet, int rownum, int height) {
        HSSFRow row = sheet.createRow(rownum);
        row.setHeightInPoints(height);
        return row;
    }

    /**
     * 创建HSSCell
     *
     * @param row
     * @param cellnum
     * @return
     */
    private static HSSFCell createCell(HSSFRow row, int cellnum) {
        HSSFCell cell = row.createCell(cellnum);
        return cell;
    }

    private static void setCellVal(HSSFCell cell, Object obj, HSSFWorkbook wb) {
        /**
         * 如果是数字类型的，按数值保存
         */
        // = wb.createCellStyle();
        if (obj == null) {

        } else if (obj instanceof String) {
            cell.setCellValue(obj.toString());
        } else if (obj instanceof BigDecimal) {
            cell.setCellValue(Double.valueOf(obj.toString()));
            cell.setCellStyle(doubleStyle);
        } else if (obj instanceof Double) {
            cell.setCellValue(Double.valueOf(obj.toString()));
            cell.setCellStyle(doubleStyle);
        } else if (obj instanceof Integer) {
            cell.setCellValue(Integer.valueOf(obj.toString()));
            cell.setCellStyle(doubleStyle);
        } else if (obj instanceof Long) {
            cell.setCellValue(Long.valueOf(obj.toString()));
            cell.setCellStyle(longStyle);
        } else if (obj instanceof Float) {
            cell.setCellValue(Float.valueOf(obj.toString()));
            cell.setCellStyle(floatStyle);
        } else if (obj.toString().matches("^-?\\d*\\.?\\d*$")) {
            cell.setCellValue(Double.valueOf(obj.toString()));
        } else {
            cell.setCellValue(obj.toString());
        }
    }
}
